package com.hq;

import com.hq.entity.AreaEntity;
import com.hq.entity.User;
import com.hq.mapper.AreaMapper;
import com.hq.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author hq
 */
public class MybatisTest {

    static String resource;
    static SqlSessionFactory sqlSessionFactory;
    static InputStream inputStream;
    static SqlSession sqlSession;

    static {
        resource = "mybatis-config.xml";

        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //new Connection()
        //这里就获取到了数据源和sql
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
    }

    @Test
    public void duo() throws SQLException {
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/chunyu_live?useSSL=false&serverTimezone=Asia/Shanghai",
                "root", "root");
        SqlSession sqlSession = sqlSessionFactory.openSession(connection);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        System.out.println(mapper.getUser("huang"));
    }
    @Test
    public  void mai1n() throws IOException {

        //SqlSession sqlSession = sqlSessionFactory.openSession();
        User huang1 = sqlSession.selectOne("com.hq.mapper.UserMapper.getUser", "huang");
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        System.out.println(mapper.getUser("huang"));
        System.out.println(mapper.getUser1("huang"));
        System.out.println(huang1);
    }

    /**
     * 多层嵌套
     * @throws IOException
     */
    @Test
    public  void forTest() throws IOException {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        ArrayList<List<Long>> lists = new ArrayList<>();
        List<Long> longs1 = Arrays.asList(1L, 2L, 3L);
        List<Long> longs2 = Arrays.asList(1L, 2L, 3L);
        List<Long> longs3 = Arrays.asList(1L, 2L, 3L);
        lists.add(longs1);
        lists.add(longs2);
        lists.add(longs3);
        mapper.test(lists);
    }

    @Test
    public void zipTest() {
        AreaMapper mapper = sqlSession.getMapper(AreaMapper.class);
        List<AreaEntity> areaList = mapper.getUser();
        for (AreaEntity areaEntity : areaList) {
            System.out.println(areaEntity);
        }

    }
}
